package com.fingard.dsp.interact.custom.hncx;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSException;
import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.diagnostics.LogHelper;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptData;
import com.fingard.dsp.bank.directConfig.FileSaveSet;
import com.fingard.dsp.bank.directConfig.ReceiptProConfig;
import com.fingard.dsp.bank.sepro.ReceiptPro;
import com.fingard.dsp.interact.*;
import com.fingard.generalobj.ExecResponse;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.ZipHelper;
import com.sunyard.insurance.ecm.socket.client.AutoScanApi;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 华农财险上传影像文件
 */
public class FileServerInvoker extends FileServerInvokerBase implements IFileServerInvoker {
    private String logCode = "hncx" + File.separator + "FileServerInvoker";

    @Override
    public void setLogCode(String pLogCode) {
        logCode = pLogCode;
    }

    @Override
    public UploadFileResp uploadFile(UploadFileReq req) {
        UploadFileResp resp = new UploadFileResp();
        resp.isCompleted = false;

        try {
            ReceiptProConfig receiptConfig = ReceiptPro.getReceiptProConfig();
            FileSaveSet fileSaveSet = receiptConfig.fileSetList.get(0);
            if ("custom.fileServer".equals(fileSaveSet.saveType)) {
                // 生成影像文件压缩包
                File localFile = new File(req.upFileLocalPath);
                String localFileDir = localFile.getParent();
                String uploadFileName = localFile.getName();
                String receiptNo = uploadFileName.substring(0, uploadFileName.indexOf("."));

                String userCode = fileSaveSet.getParam("userCode", "");
                String userName = fileSaveSet.getParam("userName", "");
                String appCode = fileSaveSet.getParam("appCode", "");
                String appName = fileSaveSet.getParam("appName", "");
                String orgCode = fileSaveSet.getParam("orgCode", "");
                String comCode = fileSaveSet.getParam("comCode", "");
                String orgName = fileSaveSet.getParam("orgName", "");
                String roleCode = fileSaveSet.getParam("roleCode", "");

                StringBuilder sbMsg = new StringBuilder();
                sbMsg.append("<?xml version=\"1.0\" encoding=\"" + fileSaveSet.getCharset("UTF-8") + "\"?>");
                sbMsg.append("<root>");
                sbMsg.append("<BASE_DATA>");
                sbMsg.append("<USER_CODE>" + userCode + "</USER_CODE>");
                sbMsg.append("<USER_NAME>" + userName + "</USER_NAME>");
                sbMsg.append("<ORG_CODE>" + orgCode + "</ORG_CODE>");
                sbMsg.append("<COM_CODE>" + comCode + "</COM_CODE>");
                sbMsg.append("<ORG_NAME>" + orgName + "</ORG_NAME>");
                sbMsg.append("<ROLE_CODE>" + roleCode + "</ROLE_CODE>");
                sbMsg.append("</BASE_DATA>");
                sbMsg.append("<META_DATA>");
                sbMsg.append("<BATCH>");
                sbMsg.append("<APP_CODE>" + appCode + "</APP_CODE>");
                sbMsg.append("<APP_NAME>" + appName + "</APP_NAME>");
                sbMsg.append("<BUSI_NO>" + receiptNo + "</BUSI_NO>");
                sbMsg.append("<COM_CODE>" + comCode + "</COM_CODE>");
                sbMsg.append("<VTREE APP_CODE=\"" + appCode + "\" APP_NAME=\"" + appName + "\">");
                sbMsg.append("<NODE BARCODE=\"\" CHILD_FLAG=\"0\" ID=\"34\" MAXPAGES=\"99999\" MINPAGES=\"0\" NAME=\"电子回单基本资料\" RESEIZE=\"800*600\" RIGHT=\"CRUDT\">");
                sbMsg.append("<NODE BARCODE=\"\" CHILD_FLAG=\"1\" ID=\"37\" MAXPAGES=\"99999\" MINPAGES=\"0\" NAME=\"电子回单文件\" RESEIZE=\"800*600\" RIGHT=\"CRUDT\"/>");
                sbMsg.append("</NODE>");
                sbMsg.append("</VTREE>");
                sbMsg.append("<PAGES>");
                sbMsg.append("<NODE ACTION=\"ADD\" ID=\"37\">");
                sbMsg.append("<PAGE FILE_NAME=\"2.jpg\" REMARK=\"备注\" UP_ORGNAME=\"" + orgName + "\" UP_TIME=\"" + Format.DateTimeFormat.format(new Date()) + "\" UP_USER=\"" + userCode + "\" UP_USER_NAME=\"" + userName + "\">");
                sbMsg.append("<PAGE_EXT>");
                sbMsg.append("<EXT_ATTR ID=\"Create SoftWare\" NAME=\"创建软件\" VALUE=\"KTU84P\"/>");
                sbMsg.append("<EXT_ATTR ID=\"CaptureTime\" NAME=\"拍摄时间\" VALUE=\"2014-09-17 15:40:49\"/>");
                sbMsg.append("<EXT_ATTR ID=\"Width x Height\" NAME=\"长 x 宽\" VALUE=\"3264 x 2448\"/>");
                sbMsg.append("<EXT_ATTR ID=\"Orientation\" NAME=\"方向\" VALUE=\"6\"/>");
                sbMsg.append("<EXT_ATTR ID=\"Flash used\" NAME=\"闪光灯模式\" VALUE=\"否\"/>");
                sbMsg.append("<EXT_ATTR ID=\"Focal length\" NAME=\"焦距长度\" VALUE=\" 3.8毫米\"/>");
                sbMsg.append("<EXT_ATTR ID=\"Aperture\" NAME=\"F 值\" VALUE=\"F/2.4\"/>");
                sbMsg.append("<EXT_ATTR ID=\"ISO equiv.\" NAME=\"ISO 速度\" VALUE=\"ISO-261\"/>");
                sbMsg.append("<EXT_ATTR ID=\"Encoding\" NAME=\"编码方式\" VALUE=\"Baseline\"/>");
                sbMsg.append("</PAGE_EXT>");
                sbMsg.append("</PAGE>");
                sbMsg.append("</NODE>");
                sbMsg.append("</PAGES>");
                sbMsg.append("</BATCH>");
                sbMsg.append("</META_DATA>");
                sbMsg.append("</root>");
                String busixml = sbMsg.toString();
                String targetReceiptDir = StringHelper.trimEnd(localFileDir, File.separator) + File.separator + receiptNo;
                String busixmlPath = targetReceiptDir + File.separator + "busi.xml";
                FileHelper.writeFile(busixmlPath, busixml, "utf-8");
                String receiptPdfPath = targetReceiptDir + File.separator + uploadFileName;
                FileHelper.copyFile(req.upFileLocalPath, receiptPdfPath);

                List<File> fileList = new ArrayList<File>();
                fileList.add(new File(busixmlPath));
                fileList.add(new File(receiptPdfPath));
                File targetZipFile = new File(targetReceiptDir + File.separator + receiptNo + ".zip");
                FileOutputStream fos2= new FileOutputStream(targetZipFile);
                ZipHelper.toZip(fileList, fos2);

                // 开始上传影像系统
                String systemID = fileSaveSet.getParam("systemID", "");
                String systemKey = fileSaveSet.getParam("systemID", "");
                String licenseStr = systemID + "#" + systemKey;
                String busiType = fileSaveSet.getParam("busiType", "");

                AutoScanApi autoScanApi = new AutoScanApi(fileSaveSet.customServerIP, Integer.parseInt(fileSaveSet.customServerPort), licenseStr);
                String tmpStrRet = autoScanApi.ScanImageFile(busiType, targetZipFile.getAbsolutePath());
                resp.appendMsgLn("响应内容："+tmpStrRet);
                String[] tmpStrRetArray = tmpStrRet.split("@");
                if ("1".equals(tmpStrRetArray[0])) {
                    // 成功
                    resp.isCompleted = true;
                    resp.appendMsgLn("上传成功");
                    resp.rtnFileId = receiptNo;
                    FGBiz.logTrace.debug(logCode, "上传成功");
                } else {
                    // 失败
                    resp.isCompleted = false;
                    resp.appendMsgLn("上传失败,失败原因:" + tmpStrRetArray[1]);
                    FGBiz.logTrace.debug(logCode, "上传失败,失败原因:" + tmpStrRetArray[1]);
                }
            } else {
                FGBiz.logTrace.error(logCode, "saveType配置有误,实际值为:" + fileSaveSet.saveType);
            }
        } catch (OSSException oe) {
            FGBiz.logTrace.exception(logCode, oe);
            resp.sbMsg.append("getStackTrace: " + LogHelper.getStackTrace(oe));
        } catch (ClientException ce) {
            FGBiz.logTrace.exception(logCode, ce);
            resp.sbMsg.append("getStackTrace: " + LogHelper.getStackTrace(ce));
        } catch (Throwable e) {
            resp.sbMsg.append(LogHelper.getStackTrace(e));
            FGBiz.logTrace.exception(logCode, e);
        }

        return resp;
    }

    @Override
    public DownloadFileResp downloadFile(DownloadFileReq req) {
        return null;
    }

    public GenerateUrlResp generateUrl(GenerateUrlReq req) {
        GenerateUrlResp resp = new GenerateUrlResp();
        resp.isCompleted = false;
        resp.sbMsg.append("未实现该接口");
        return resp;
    }

    @Override
    public ExecResponse pushData(ArrayList<ReceiptData> pDataList) {
        ExecResponse resp = new ExecResponse();
        resp.logMsg = "不需实现";
        return resp;
    }
}